# -*- coding: utf-8 -*-
import logging

import xinge
from django.conf import settings
from xinge import MessageIOS, Message

_LOGGER = logging.getLogger(__name__)
_XINGE_IOS_CONF = settings.XINGE_IOS_CONF
# TODO: 安卓有马甲包，包名不同
_XINGE_IOS_ACCESS_ID = settings.XINGE_IOS_ACCESS_ID
_XINGE_IOS_SECRET = settings.XINGE_IOS_SECRET
_XINGE_IPAD_ACCESS_ID = settings.XINGE_IPAD_ACCESS_ID
_XINGE_IPAD_SECRET = settings.XINGE_IPAD_SECRET
_APNS_ENV = settings.APNS_ENV
_XINGE_ANDROID_ACCESS_ID = settings.XINGE_ANDROID_ACCESS_ID
_XINGE_ANDROID_SECRET = settings.XINGE_ANDROID_SECRET


def push_to_android(user_id, title, body, payload):
    ret_status, ret_msg = xinge.PushAccountAndroid(
        _XINGE_ANDROID_ACCESS_ID, _XINGE_ANDROID_SECRET, title, payload, body, user_id)
    _LOGGER.info('push notification to android with return: %s, %s, uid: %s',
                 ret_status, ret_msg, user_id)


def push_to_ios(user_id, title, body, payload):
    ret_status, ret_msg = xinge.PushAccountIos(
        _XINGE_IOS_ACCESS_ID, _XINGE_IOS_SECRET,
        body, payload, user_id, _APNS_ENV)
    _LOGGER.info('push notification to iOS with return: %s, %s, uid: %s',
                 ret_status, ret_msg, user_id)


def push_to_ipad(user_id, title, body, payload):
    return
    # ret_status, ret_msg = xinge.PushAccountIos(
    #     _XINGE_IPAD_ACCESS_ID, _XINGE_IPAD_SECRET,
    #     body, payload, user_id, _APNS_ENV)
    # _LOGGER.info('push notification to iPad with return: %s, %s, uid: %s',
    #              ret_status, ret_msg, user_id)


def push_to_all_android(payload):
    push = xinge.XingeApp(_XINGE_ANDROID_ACCESS_ID, _XINGE_ANDROID_SECRET)
    msg = Message()
    msg.title = payload['title']
    msg.content = payload['content']
    msg.sendTime = payload['send_time']
    msg.custom = {'command': payload['command']}
    msg.type = 1
    ret = push.PushAllDevices(0, msg)
    _LOGGER.info('push notification to all android with return %s, %s, %s' % ret)


def push_to_all_ios(payload):
    for k, v in _XINGE_IOS_CONF.items():
        access_id = v['access_id']
        secret_key = v['secret_key']
        push = xinge.XingeApp(access_id, secret_key)
        msg = MessageIOS()
        msg.alert = payload['content']
        msg.sendTime = payload['send_time']
        msg.custom = {'command': payload['command']}
        ret = push.PushAllDevices(0, msg, 1)
        _LOGGER.info('push ios notiification access_id: %s' % access_id)
        _LOGGER.info('push notification to all ios with return: %s, %s, %s' % ret)
